<?php

namespace app\api\controller;

use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Sku;
use app\admin\model\product\Value;
use app\admin\model\user\Finance;
use think\Db;
use think\Request;
use app\common\controller\Api;
use think\Validate;

class Productlisto extends Api
{
    protected static $model = null;
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Listo();
    }

    /**
     * 商品结算
     */
    public function preOrder()
    {
        $data = input('data');

        if (!$data) {
            $this->error('参数缺失！');
        }

        $dataArr = [];
        $data1 = explode('|', $data);
        foreach ($data1 as $v1) {
            $arr1 = explode(',', $v1);
            $item = [];
            foreach($arr1 as $v2){
                $arr2 = explode(':',$v2);
                if($arr2[0] == 'sku_id'){
                    $item['sku_id'] = $arr2[1];
                }elseif ($arr2[0] == 'number'){
                    $item['number'] = $arr2[1];
                }
            }

            $dataArr[] = $item;
        }

//        $dataArr = json_decode($data, true);

        if (count($dataArr) <= 0) {
            $this->error('请至少选择一个商品！');
        }

        $id = $this->auth->id;
        $finance = Finance::where('user_id', $id)->find();
        $tag = create_order($id);
        $list = [];
        $mark = '';
        foreach ($dataArr as $v) {
            if ($v['sku_id'] <= 0) {
                $this->error('商品规格缺失！');
            }
            $skuInfo = Sku::find($v['sku_id']);
            if ($skuInfo->stock < $v['number']) {
                $this->error('商品余量不足！');
            }
            $productInfo = Lists::where('id', $skuInfo->product_id)->find();
            $cmark = Category::where('id', $productInfo->category_id)->value('mark');
            if ($mark == '') {
                $mark = $cmark;
            } else {
                if ($cmark != $mark) {
                    $this->error('一次只能购买一个种类的商品！');
                }
            }

            if ($cmark == 'bill' && $finance->hasscore > 0) {
                $this->error('积分余额尚未耗尽，不可购买报单产品！');
            }

            $attrs_arr = json_decode($skuInfo->attrs, true);
            $vals = [];
            foreach ($attrs_arr as $v1) {
                $arr = explode(':', $v1);
                $value_name = Value::where('id', $arr[1])->value('name');
                array_push($vals, $value_name);
            }

            $parameters = implode('/', $vals);
            $time = time();
            $item = [
                'product_id' => $skuInfo->product_id,
                'product_name' => $productInfo->name,
                'num' => $v['number'],
                'user_id' => $id,
                'tag' => $tag,
                'sku_id' => $v['sku_id'],
                'parameters' => $parameters,
                'price' => $skuInfo->price,
                'total' => $skuInfo->price * $v['number'],
                'createtime' => $time,
                'updatetime' => $time
            ];
            array_push($list, $item);
        }

        $res = self::$model->insertAll($list);
        if ($res) {
            $this->success('生成商品清单！', $tag);
        } else {
            $this->error('操作失败！');
        }
    }

    /**
     * 获取商品清单
     */
    public function getOrder()
    {
        $user_id = $this->auth->id;
        $tag = input('tag');
        $lists = self::$model->field('id,product_id,product_name,num,price,parameters,total')->where("tag", $tag)->where('user_id', $user_id)->order('id desc')->select();

        $total = $num = $transfee = 0;
        foreach ($lists as &$val) {
            $pInfo = Lists::where('id', $val['product_id'])->find();
//            $val['goodname'] = $pInfo['goodname'];
            $val['cover_ico'] = make_full_url($pInfo['image']);
            $val['intro'] = $pInfo['intro'];

            $total += $val['total'];
            $num += $val['num'];        //商品数量
            $transfee += $pInfo['transfee'] * $val['num'];
        }

        $data = [
            'list' => $lists,
            'transfee' => $transfee,
            'num' => $num,
            'total' => $total,
        ];

        $this->success('商品清单！', $data);
    }

    public function search()
    {
        /*类别id*/
        $categoryid = input('cateid', '');
        $this->assign('cateid', $categoryid);
        /*关键词*/
        $keyword = input('keyword', '');
        $this->assign('keyword', $keyword);
        /*排序*/
        $sort = input('sort', 'changetime');
        $this->assign('sort', $sort);
        $order = $sort . ' desc';
        if ($sort == 'member_price') {
            $order = $sort . ' asc';
        }
        //根据id查询此种类下的前8条数据
        if ($categoryid) {
            $map['category_id'] = $categoryid;

        }

        $map['status'] = 1;
        if ($keyword) {
            $map ['goods_name|goods_introduct|goods_detail'] = array('like', '%' . $keyword . '%');

        }
        $categoryList = Db('shop')->where($map)->order($order)->select();
        $this->assign('categoryLists', $categoryList);

        $this->assign('title', '分类页商品');
        return $this->fetch();
    }
}